#include "ControlLabWindow.h"
#include "ControlLabAboutDialog.h"
#include "PluginMgr.h"
#include <wx/dynlib.h>

enum{
	ID_DOIT = 500
};

IMPLEMENT_CLASS(ControlLabWindow, wxFrame)

BEGIN_EVENT_TABLE(ControlLabWindow, wxFrame)
	EVT_BUTTON(ID_DOIT, ControlLabWindow::OnDoit)
END_EVENT_TABLE()

ControlLabWindow::ControlLabWindow( wxWindow* parent )
:
ControlLabFrame( parent )
{
	
	PluginMgr *pm = new PluginMgr();
	wxTreeItemId newID = new wxTreeItemId();
	if(!pm->loadConfig()){
		//if there isn't a plugin_config.xml file, read in plugins to create one
		wxMessageBox(wxT("Couldn't find plugin_config.xml. Trying to make one..."));
		pm->saveConfig();
		if(!pm->loadConfig()){
			wxMessageBox(wxT("Couldn't create/load plugin_config.xml"));
			Close();
		}
	}
	//load up the design tree with plugins so we can get them later
	wxTreeItemId rootID = m_treeCtrlDesign->AddRoot(wxT("/"));
	PluginHouse pluginHouse ;
	pluginHouse = pm->first();
	while(!pm->end()){
		//@TODO Use tree_path so plugins get sorted into categories
		newID = m_treeCtrlDesign->AppendItem(rootID, pluginHouse.plugin_name);
		pluginHouse = pm->next();
	}
}

void ControlLabWindow::onExitClicked( wxCommandEvent& event )
{
	Close();
}

void ControlLabWindow::onAboutClicked( wxCommandEvent& event )
{
	ControlLabAboutDialog* about = new ControlLabAboutDialog(this);
	about->ShowModal();
	about->Destroy();
}
void ControlLabWindow::onNewProjectSelected( wxCommandEvent& event ){
	OnDoit(event);
}
void ControlLabWindow::OnDoit(wxCommandEvent& e){
	//Load the plugin
	wxDynamicLibrary dll;
	dll.Load(wxGetCwd()+_("/")+wxDynamicLibrary::CanonicalizeName(_("samplePlugin")));
	if(dll.IsLoaded()){
		//Create a valid function pointer using the function pointer type in plugin.h
		wxDYNLIB_FUNCTION(CreatePlugin_function,CreatePlugin,dll);
		//check if the function is found
		if(pfnCreatePlugin){
			//Important: Use Detach(), otherwise the DLL will be unloaded once the wxDynamibLibrary object
			//goes out of scope
			dll.Detach();
			//Create the plugin
			Plugin* plugin = pfnCreatePlugin();
			//call some method in it
			plugin->PerformTasks();
			//we will append the gui from the plugin into the panel's sizer
			wxBoxSizer* s = new wxBoxSizer(wxVERTICAL);
			 
			wxWindow* w = plugin->GetGUI(m_panel_display);
			s->Add( w, 0, wxALL|wxALIGN_CENTER, 5 );
			m_panel_display->SetBackgroundColour( wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT ) );
			m_panel_display->SetSizer( s );
			m_panel_display->Layout();
		}
	}

}
